﻿

using IoTClient;
using IotClientService.Models.Lg;
using IotClientService.Services;
using IotContract.Enums;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using XT.Common.Extensions;

namespace IotClientService.Handles.lgs;
/// <summary>
/// 外观检测
/// </summary>
public class LgHandleInspect:LgHandleBase
{
    public LgHandleInspect(ILgApiService lgCallApiService) : base(lgCallApiService)
    {
    }

    /// <summary>
    /// 设备类型
    /// </summary>
    public override IotEquipType EquipType { get; set; } = IotEquipType.INSPECT;
    /// <summary>
    /// 处理消息
    /// </summary>
    /// <param name="msg"></param>
    /// <returns></returns>
    /// <exception cref="NotImplementedException"></exception>
    public override async Task<bool> HandleMsg(LgMsgInfo msg)
    {
        string replyCmd = string.Empty;
        switch (msg.Command)
        {
            // 作业实处理Data报告
            case "901":
                replyCmd = "902";
               await Handle901(msg, replyCmd);
                break;

            // 设备状态报告指示回应
            case "910":
               await Handle910(msg, "910");
                // send 833 

                break;
            // 设备状态报告
            case "913":
              await  Handle913(msg, "913");

                break;
            // 作业mode报告
            case "917":
                replyCmd = "918";
              await  Handle917(msg, replyCmd);
                break;
            // 通信状态报告邀请
            case "925":
                replyCmd = "926";
              await  Handle925(msg, replyCmd);
                break;
            // 通信状态报告回应
            case "926":
               await Handle926(msg, "926");
                break;
            // 电芯投入报告
            case "933":
                replyCmd = "934";
               await Handle933(msg, replyCmd);
                break;

            // 未知命令,错误
            case "981":
               await Handle981(msg, "981");
                break;
            // 设备Trouble报告
            case "985":
              await  Handle985(msg, "985");
                break;


            // 设置时间指示
            case "999":
               await Handle999(msg, "999");
                break;
            default:
                // send 981,
               await Handle981(msg, "981");
                break;
        }
        return true;
    }
    /// <summary>
    /// 作业实处理Data报告
    /// </summary>
    /// <param name="msg"></param>
    /// <param name="replyCmd"></param>
    private async Task Handle901(LgMsgInfo msg, string replyCmd)
    {
        var sendMsg = new LgMsgInfo
        {
            Direction = 0,
            ObjID = msg.ObjID,
            HasMsg = 0,
            SeqNo = msg.SeqNo,
            Command = replyCmd,

        };
        List<LgInspectResult> datas = new List<LgInspectResult>();
        // 数量
        int count = msg.Message.Substring(18, 1).To<int>();
      
        for(int i=0; i<count; i++)
        {
            var result = msg.Message.Substring(19 + 71 * i, 71);
            LgInspectResult lgInspect = new LgInspectResult
            {
                CellId = result.Substring(0, 24),
                IsNg=result.Substring(24,1).To<int>(),
                NgCode=result.Substring(25,4),
                FeedTime = DateTime.ParseExact(result.Substring(29, 14), "yyyyMMddHHmmss", CultureInfo.InvariantCulture).ToString("yyyy-MM-dd HH:mm:ss"),
                DischargeTime= DateTime.ParseExact(result.Substring(43, 14), "yyyyMMddHHmmss", CultureInfo.InvariantCulture).ToString("yyyy-MM-dd HH:mm:ss"),
                FrontSide3dCamera = result.Substring(57,1).To<int>(),
                FrontSide2dCamera=result.Substring(58,1).To<int>(),
                FrontBottomEdge3dCamera=result.Substring(59,1).To<int>(),
                BackRightSide3dCamera=result.Substring(60,1).To<int>(),
                BackRightSide2dCamera=result.Substring(61,1).To<int>(),
                BackBottomEdge3dCamera=result.Substring(62,1).To<int>(),
                PoleCylinderSurface3dCamera=result.Substring(63,1).To<int>(),
                PoleCylinderSurface2dCamera=result.Substring(64,1).To<int>(),
                BottomSurface3dCamera=result.Substring(65,1).To<int>(),
                BottomSurface2dCamera=result.Substring(66,1).To<int>(),
                LeftMiddleEdge3dCamera=result.Substring(67,1).To<int>(),
               RightMiddleEdge3dCamera=result.Substring(68,1).To<int>(),
               ExplosionProofValve2dCamera=result.Substring(69,1).To<int>(),
               LeftRightPoleCylinder2dCamera=result.Substring(70,1).To<int>()

            };
            datas.Add(lgInspect);
        }


        var rep= await Api.CommitInspectResult(new Models.Lg.Remote.LgInspectResultRequest
        {
            EquipNum=Equip.Num,
            EquipType = this.EquipType,
            ProgramType = Equip.ProgramType,
            Cnt = count,
            Datas = datas
        });
        
        if (!rep.Success)
        {
            Equip.ExMessage = rep.Message;
           
            msg.Body ="1";
            await Handle981(msg, "981");
            return;
        }
        // 构造数据 29*2（电芯数目）
        string str = "";
        foreach (var item in rep.Result)
        {
            // 24长度
            var cellid = item.Cell.PadRight(24, ' ');
            // 0:ok 1:ng
            var ret = item.Ret;
            var ng = item.NgCode.PadLeft(4,'0');
            str += $"{cellid}{ret}{ng}";
        }

        sendMsg.Body = str;
        sendMsg.IsSend = true;
        InvokeSend(sendMsg);


    }


   

    /// <summary>
    /// 电芯投入报告
    /// </summary>
    /// <param name="msg"></param>
    /// <param name="replyCmd"></param>
    private async Task Handle933(LgMsgInfo msg, string replyCmd)
    {
        var sendMsg = new LgMsgInfo
        {
            Direction = 0,
            ObjID = msg.ObjID,
            HasMsg = 0,
            SeqNo = msg.SeqNo,
            Command = replyCmd,

        };
        // 托盘
        var cellid = msg.Message.Substring(18, 24);

       
        Equip.Obj = cellid;

        var result= await Api.CommitCellEnter(new Models.Lg.Remote.LgCellEnterRequest
        {
            Cell = cellid,
            EquipType = this.EquipType,
            EquipNum = Equip.Num,
            ProgramType = Equip.ProgramType
        });
        // 0:ok 1:ng
        int ret = 0;
        if (!result.Success)
        {
            Equip.ExMessage = result.Message;
            ret = 1;
        }
        else
        {
            ret = result.Result?.Ret ?? 1;
        }
        if (ret == 1)
        {
            msg.Body = ret.ToString();
            await Handle981(msg, "981");
            return;
        }


        #region 传输body

        var cell = cellid;
       
        var ngCode = result.Result?.NgCodes?.FirstOrDefault() ?? "0000";

        #endregion
        sendMsg.Body = $"{cell}{ret}{ngCode}";
        sendMsg.IsSend = true;
        InvokeSend(sendMsg);
    }

  


  
}
